package com.eastcom.providor.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.eastcom.bm.atom.Atom_MetalKpiBase;
import com.eastcom.bm.atom.Atom_MetalKpiExpand;
import com.eastcom.common.util.UUIDHexGenerator;
import com.eastcom.providor.dao.IMetalKpiBaseDao;
import com.eastcom.providor.dao.IMetalKpiExpandDao;
import com.eastcom.providor.service.impl.MetalKpiBaseService;
import com.eastcom.providor.service.impl.MetalKpiExpandService;

public class UploadFileServlet extends HttpServlet{

	private final int flushSize = 1024 * 512; 
	
	private final long fileSize = 10 * 1024 * 1024;
	
	private UUIDHexGenerator uuid=new UUIDHexGenerator();
	
	private MetalKpiExpandService metalKpiExpandService;
	
	private MetalKpiBaseService metalKpiBaseService;
	
	public static String applicationContextPath;
	
	public void init() throws ServletException {
		ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext(applicationContextPath);
		metalKpiBaseService=new MetalKpiBaseService();
		metalKpiBaseService.setMetalKpiBaseDao((IMetalKpiBaseDao)context.getBean("metalKpiBaseDao"));
		
		metalKpiExpandService=new MetalKpiExpandService();
		metalKpiExpandService.setMetalKpiExpandDao((IMetalKpiExpandDao)context.getBean("metalKpiExpandDao"));
		System.out.println(new Date()+" UploadFileServlet init completed");
	}
	
	public void doProcess(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		//FileItemFactory factory = new DiskFileItemFactory();
		
		try {
			 DiskFileItemFactory factory = new DiskFileItemFactory();
			 factory.setSizeThreshold(flushSize);
			 ServletFileUpload upload = new ServletFileUpload(factory);
			 upload.setSizeMax(fileSize);
			 
		     List<FileItem> list = upload.parseRequest(request);
		     Workbook rwb=null;
		     for (int i = 0; i < list.size(); i++) {  
		         FileItem fileItem = list.get(i);   
		         
		         try{
		        	 rwb=Workbook.getWorkbook(fileItem.getInputStream());
		        	 loadDataByFile(rwb);
		             System.out.println(fileItem.getName());
		             //String name = fileItem.getName().substring(fileItem.getName().lastIndexOf("//") + 1);  
		         }
		         catch(Exception e){
		        	 e.printStackTrace();
		         }
		         finally{
		        	 if(rwb!=null)
		        		 rwb.close();
		         }
		     }
		} 
        catch (Exception e) {  
		     e.printStackTrace();  
		}
	}
	
	public void loadDataByFile(Workbook rwb) throws Exception{
		List<Atom_MetalKpiBase> metalKpiBases=new LinkedList<Atom_MetalKpiBase>();
		List<Atom_MetalKpiExpand> metalKpiExpands=new LinkedList<Atom_MetalKpiExpand>();
		
		Map<Object, Map> versionMap=metalKpiExpandService.selectKpiLastVersion();
		
		Sheet[] sheets = rwb.getSheets();
		for(Sheet sheet:sheets){
			for(int row=1;row<sheet.getRows();row++){
				Cell[] cells=sheet.getRow(row);
				
				if(cells==null||cells.length==0)
					continue;
				
				metalKpiBases.add(wrapMetalKpiBase(cells));
				Atom_MetalKpiExpand expand=wrapMetalKpiExpand(cells);
				
				Map vp=versionMap==null?null:versionMap.get(expand.getKpiBaseDefine().getId());
				Integer version=vp==null||vp.get("version")==null?0:Integer.parseInt((String)vp.get("version"))+1;
				expand.setVersion(version.toString());
				metalKpiExpands.add(expand);
			}
		}
		
		//metalKpiBaseService.deleteMetalKpiBases(metalKpiBases);
		metalKpiBaseService.saveMetalKpiBase(metalKpiBases);
		metalKpiExpandService.saveMetalKpiBase(metalKpiExpands);
	}
	
	private Atom_MetalKpiBase wrapMetalKpiBase(Cell[] cells){
		Atom_MetalKpiBase metalKpiBase=new Atom_MetalKpiBase();
		
		metalKpiBase.setId(cells[0].getContents());
		metalKpiBase.setCn_name(cells[1].getContents());
		metalKpiBase.setDesc(cells[2].getContents());
		metalKpiBase.setBusinessId(cells[3].getContents());
		metalKpiBase.setType(cells[4].getContents());
		//metalKpiBase.setSubType(cells[5].getContents());
		metalKpiBase.setRelatedKpis(cells[5].getContents());
		
		return metalKpiBase;
	}
	
	private Atom_MetalKpiExpand wrapMetalKpiExpand(Cell[] cells){
		Atom_MetalKpiExpand metalKpiExpand=new Atom_MetalKpiExpand();
		Atom_MetalKpiBase metalKpiBase=new Atom_MetalKpiBase();
		
		metalKpiExpand.setId(uuid.generate().toString());
		metalKpiBase.setId(cells[0].getContents());
		metalKpiExpand.setKpiBaseDefine(metalKpiBase);
		//metalKpiExpand.setVersion(cells[7].getContents());
		metalKpiExpand.setGranularity(cells[6].getContents());
		metalKpiExpand.setDimension(cells[7].getContents());
		metalKpiExpand.setSourceDesc(cells[8].getContents());
		metalKpiExpand.setArithmetic(cells[9].getContents());
		metalKpiExpand.setDelay(cells[10].getContents());
		metalKpiExpand.setCollectDesc(cells[11].getContents());
		metalKpiExpand.setUpdateTime(new Date());
		metalKpiExpand.setUpdateName(cells[12].getContents());
		
		return metalKpiExpand;
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doProcess(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doProcess(request, response);
    }

}
